上篇講到生命週期主要分成以下四大類:
Update 有五個生命週期
不要依賴這個方法來「避免」 render
效能最佳化
官方表示 getDerivedStateFromProps
/ shouldComponentUpdate
/ getSnapshotBeforeUpdate
這三個生命週期比較少使用。
利用 console.log() 印出生命週期
ParentLifeCycle
import React, { Component } from 'react';
import ChildLifeCycle from './ChildLifeCycle';
class ParentLifeCycle extends Component {
constructor(props) {
super(props);
this.state = {
name: 'aaaa',
}
console.log('Parent Constructor');
}
static getDerivedStateFromProps(nextProps, prevState) {
console.log('Parent getDerivedStateFromProps');
// 回傳 null 表示 state 無異動
return null;
}
componentDidMount() {
console.log('Parent componentDidMount');
}
shouldComponentUpdate(nextProps, nextState, nextContext) {
console.log('Parent shouldComponentUpdate');
// 預設值為 true
return true;
}
getSnapshotBeforeUpdate(prevProps, prevState) {
console.log('Parent getSnapshotBeforeUpdate');
return null;
}
componentDidUpdate() {
console.log('Parent componentDidUpdate');
}
render() {
console.log('Parent render');
return (
<div>
<div>Parent LifeCycle</div>
<ChildLifeCycle />
</div>
)
}
}
export default ParentLifeCycle;
ChildLifeCycle
import React, { Component } from 'react';
class ChildLifeCycle extends Component {
constructor(props) {
super(props);
this.state = {
test: 'aaaa',
}
console.log('Child Constructor');
}
static getDerivedStateFromProps(nextProps, prevState) {
console.log('Child getDerivedStateFromProps');
// 回傳 null 表示 state 無異動
return null;
}
componentDidMount() {
console.log('Child componentDidMount');
}
shouldComponentUpdate(nextProps, nextState, nextContext) {
console.log('Child shouldComponentUpdate');
// 預設值為 true
return true;
}
getSnapshotBeforeUpdate(prevProps, prevState) {
console.log('Child getSnapshotBeforeUpdate');
return null;
}
componentDidUpdate() {
console.log('Child componentDidUpdate');
}
render() {
console.log('Child render');
return (
<div>
<div>Child LifeCycle</div>
</div>
)
}
}
export default ChildLifeCycle;
下面截圖網頁呈現目前只有載入的生命週期
加入更新狀態的 click 事件
changeName = () => {
this.setState({
name: 'changeName'
});
}
render() {
console.log('Parent render');
return (
<div>
<div>Parent LifeCycle</div>
<button onClick={this.changeName}>update state</button>
<ChildLifeCycle />
</div>
)
}
再次查看按了change state
的 console.log
只有一個 componentWillUnmount()